package com.stox.client.core.model;

import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import com.stox.client.core.model.intf.Navigable;
import com.stox.client.core.model.intf.Searchable;

public class SearchableDecorator<T> implements Searchable {

	private Navigable<T> navigable;
	
	public SearchableDecorator(Navigable<T> navigable) {
		this.navigable = navigable;
	}
	
	@Override
	public Navigable<?> getNavigable() {
		return navigable;
	}

	@Override
	public void search(String text, boolean forward, boolean current) {
		T entity = navigable.current();
		entity = null == entity ? 	(forward ? 	navigable.first() : 
												navigable.last()) : 
									(forward ? 	(current ? 	navigable.next(entity) : 
															navigable.first()) : 
												( current ? navigable.previous(entity) : 
															navigable.last()));
		
		
		try{
			Pattern pattern = Pattern.compile(text.trim(), Pattern.CASE_INSENSITIVE);
			while(null != entity){
				if(pattern.matcher(entity.toString()).find()){
					navigable.scrollClearAndSelect(entity);
					break;
				}
				entity = forward ? navigable.next(entity) : navigable.previous(entity);
			}
		}catch(PatternSyntaxException ignored){}
		
	}

}
